package pl.medec.formmanager.controllers 
{
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.MouseEvent;

	/**
	 * @author medec
	 */
	public class CheckboxController 
	{
		private var _view:MovieClip;
		public var required:Boolean;
		private var errorInfoDisplayObject:DisplayObject;
		private var _isSelected:Boolean;
		private var errorInfoString:String;
		private var errorInfoFunction:Function;

		public function CheckboxController(checkbox:MovieClip, required:Boolean = false, errorInfo:* = null) 
		{
			this._view = checkbox;
			this.required = required;
            
			if(errorInfo) 
			{
				if(errorInfo is DisplayObject) 
				{
					this.errorInfoDisplayObject = errorInfo as DisplayObject;
				}
				else if(errorInfo is String) 
				{
					this.errorInfoString = errorInfo as String;
				}
				else if(errorInfo is Function) 
				{
					this.errorInfoFunction = errorInfo as Function;
				}
			}
        	
			if(this.errorInfoDisplayObject) 
			{
				this.errorInfoDisplayObject.visible = false;
			}
            
			this._view.gotoAndStop( 1 );
        	
			this._view.buttonMode = true;
			this._view.addEventListener( MouseEvent.CLICK, onCheckboxClick, false, 0, true );
		}

		public function toString():String 
		{
			return "CheckboxController " + this._view.name;
		}

		private function onCheckboxClick(event:MouseEvent):void 
		{
			this.selected = !this.selected;
		}

		public function get selected():Boolean 
		{
			return _isSelected;
		}

		public function set selected(isSelected:Boolean):void 
		{
			_isSelected = isSelected;
            
			if(isSelected) 
			{
				this._view.gotoAndStop( 2 );
			}
			else 
			{
				this._view.gotoAndStop( 1 );
			}
            
            
			if(this.errorInfoDisplayObject) 
			{
				this.errorInfoDisplayObject.visible = false;
			}
			else if(this.errorInfoDisplayObject) 
			{
				this.errorInfoDisplayObject.visible = false;
			}
		}        

		public function destroy():void 
		{
			this._view.removeEventListener( MouseEvent.CLICK, onCheckboxClick );
		}

		public function validate(isBrutalValid:Boolean = false, isValid:Boolean = false):Boolean 
		{
			var result:Boolean;
			if(!isBrutalValid) 
			{
				result = this.selected;
			}
			else 
			{
				result = isValid;
			}
            
			if(!result && this.errorInfoDisplayObject) 
			{
				this.errorInfoDisplayObject.visible = true;
			}
            else if(result && this.errorInfoDisplayObject) 
			{
				this.errorInfoDisplayObject.visible = false;
			}
            
			if(!result && this.errorInfoFunction != null) 
			{
				this.errorInfoFunction( ); 
			}
            
			return result;
		}
		
		public function get view():MovieClip
		{
			return _view;
		}
	}
}
